<template>
    <Row gutter="16">
        <Col span="24">
        <Card :bordered="false">
            <Tabs value="roleItems">
                <TabPane label="我的权限" name="myPermission">标签一的内容</TabPane>
                <TabPane label="用户列表" name="userItems">标签二的内容</TabPane>
                <TabPane label="角色列表" name="roleItems">
                    <Table highlight-row :loading="loading" stripe border :columns="roleColumns" :data="roleRows"
                           @on-current-change="roleHandleRowChange" @on-row-click="rowClickRole"></Table>

                    <div style="margin: 10px;overflow: hidden">
                        <div style="float: right;">
                            <Page :total="total" show-total="true" placement="top" show-sizer
                                  @on-change="goPage"></Page>
                        </div>
                    </div>

                </TabPane>
            </Tabs>
        </Card>
        <Spin fix size="large" fix v-if="spinShowWin">
            <Icon type="load-c" size="18" class="demo-spin-icon-load"></Icon>
            <div>提交中...</div>
        </Spin>
        </Col>

        <Spin fix size="large" fix v-if="spinShow">
            <Icon type="load-c" size="18" class="demo-spin-icon-load"></Icon>
            <div>提交中...</div>
        </Spin>

        <floatPanel v-model="showPanel" @on-break="breakContent">
            <p slot="right">
                <Tooltip content="保存" placement="bottom-start">
                    <Button type="info" :disabled="opDisabled" shape="circle" icon="android-done"
                            @click="savePermission()"></Button>
                </Tooltip>

                <Tooltip content="刷新" placement="bottom-start">
                    <Button type="success" :disabled="opDisabled" shape="circle" icon="refresh"
                            @click="loadMenuData()"></Button>
                </Tooltip>
            </p>
            <Card shadow>
                <Row>
                    <Col span="12">
                    <Input v-model="searchValue" icon="search" placeholder="输入关键字" size="large"></Input>
                    <Tree ref="menuTree" :data="menusData" show-checkbox @on-select-change="selectMenu"
                          @on-check-change="checkMenu"></Tree>
                    </Col>
                    <Col span="12">
                    <Table ref="menuTable" highlight-row :loading="loadingOp" stripe border :columns="columns" :data="rows"
                           @on-select="selectRole" @on-select-cancel="selectCancelRole"
                           @on-select-all="selectAllRole"></Table>
                    </Col>
                </Row>
            </Card>
            </div>

            <Spin fix size="large" fix v-if="spinShow">
                <Icon type="load-c" size="18" class="demo-spin-icon-load"></Icon>
                <div>提交中...</div>
            </Spin>
        </floatPanel>
    </Row>

</template>
<script>
    import Util from '@/libs/util'
    import floatPanel from '@/components/float-panel'

    let qs = require('qs');
    export default {
        components: {
            floatPanel
        },
        data() {
            return {
                showPanel: false,
                spinShowWin: false,
                hidePanel: false,
                spinShow: false,
                loading: false,
                loadingOp: false,
                spinShowPanel: false,
                opDisabled: true,
                selectRoleId: '',
                searchValue: '',
                index: 0,
                total: 0,
                menusData: [],
                roleRows: [],
                checkRows: [],
                hashMenus: {},
                roleColumns: [
                    {
                        title: '角色名称',
                        key: 'roleName',
                        editable: true
                    },
                    {
                        title: '角色编码',
                        key: 'permission',
                        //fixed: 'left'
                    },
                    {
                        title: '当前状态',
                        key: 'roleStatus',
                        render: (h, params) => {
                            let roleStatus = params.row.roleStatus;
                            return h('div', [
                                h('Tag', {
                                    props: {
                                        color: roleStatus == 1 ? "green" : "red"
                                    },
                                    on: {
                                        "on-change": (status) => {

                                        }
                                    }
                                }, roleStatus == 1 ? "启用" : "停用"),
                            ]);
                        }
                    }
                ],
                columns: [
                    {
                        type: 'selection',
                        align: 'center',
                    },
                    {
                        title: '资源名称',
                        key: 'MENUNAME',
                        align: 'center'
                    },
                    {
                        title: '资源编码',
                        key: 'PERMISSION',
                        align: 'center'
                    },
                    {
                        title: '路由地址',
                        key: 'MENUURL',
                        align: 'center'
                    }
                ]
            }
        },
        methods: {
            handleStart() {
                let lastPath = sessionStorage.getItem("lastPath");
                this.$router.push({path: lastPath});
            },
            loadMenuData() {
                let me = this;
                me.spinShow = true;
                Util.axios.post('/ms/menus/queryAll', {}).then(res => {
                    me.spinShow = false;
                    var data = res.data;
                    if (data.result) {
                        me.menusData = data.data;
                    }
                });
            },
            /**
             * 查询列表
             */
            queryRoleList() {
                var me = this;
                me.loading = true;
                let page = {'size': 10, 'page': this.index};
                Util.axios.post('/ms/role/query', qs.stringify(page)).then(res => {
                    var data = res.data;
                    if (data.result) {
                        me.total = data.data.total;
                        me.roleRows = data.data.rows;
                    }
                    me.loading = false;
                });
            },
            /**
             * 翻页
             * @param index
             */
            goPage(index) {
                this.index = index - 1;
                this.loadMenuData();
            },
            roleHandleRowChange(currentRow, oldCurrentRow) {
            },
            rowClickRole(row, index) {
                let me = this;
                me.showPanel = true;
                me.hidePanel = true;
                me.spinShowWin = true;
                me.spinShowPanel = true;
                me.selectRoleId = row.roleId;
                Util.axios.post('/ms/acl/findByRoleIds', qs.stringify({roleId: row.roleId})).then(res => {
                    me.spinShowPanel = false;
                    let data = res.data;
                    if (data.result) {

                        me.opDisabled = false;
                        //转成hash
                        me.hashMenus = {};
                        let setMenu2Hash = function (array) {
                            array.map(key => {
                                let hashKey = key.MENUID;
                                me.hashMenus[hashKey] = hashKey;
                            });
                        }
                        setMenu2Hash(data.data);
                        //遍历菜单，勾选
                        if (data.data && data.data.length > 0) {
                            let iteration = function (array) {
                                array.forEach(ref => {
                                    let menuId = ref.id;
                                    let obj = me.hashMenus[menuId];
                                    ref.checked = false;
                                    if (Array.isArray(ref.children)) {
                                        iteration(ref.children);
                                    } else if (obj) {
                                        ref.checked = true;
                                    }
                                });
                            }
                            iteration(me.menusData);
                        }
                        else {
                            let iteration = function (array) {
                                array.forEach(ref => {
                                    ref.indeterminate = false;
                                    ref.checked = false;
                                    if (Array.isArray(ref.children)) {
                                        iteration(ref.children);
                                    }
                                });
                            }
                            iteration(me.menusData);
                        }
                    }
                });
            },
            savePermission() {
                let me = this;
                const flatTree = [];
                //菜单树数据
                let data = me.$refs['menuTree'].data;
                let menuTable = me.$refs.menuTable.objData;
                for (let t in menuTable)
                {
                    let tab = menuTable[t];
                    if(tab._isChecked){
                        flatTree.push(tab.MENUID);
                    }
                }
                //迭代勾选、半勾选的数据
                let iteration = function (array) {
                    array.forEach(ref => {
                        if (ref.indeterminate || ref.checked) {
                            flatTree.push(ref.id);
                        }
                        if (Array.isArray(ref.children)) {
                            iteration(ref.children);
                        }
                    });
                }
                iteration(data);

                if (flatTree) {
                    me.spinShow = true;
                    Util.axios.post('/ms/acl/save', qs.stringify({
                        menuIds: flatTree.join(","),
                        roleId: me.selectRoleId
                    })).then(res => {
                        me.spinShow = false;

                        me.hashMenus = [];
                        flatTree.map(key => {
                            me.hashMenus[key] = key;
                        });

                        if (res.data.result) {
                            me.$Message.success(res.data.msg);
                        }
                        else {
                            me.$Message.success(res.data.msg);
                        }
                    });
                }

            },
            /**
             * 选择菜单
             * @param nodeKey
             */
            selectMenu(nodeKey) {
                let me = this;
                let node = me.$refs['menuTree'].getSelectedNodes();
                me.selectItem = nodeKey;
                me.showParent = false;
                //查询节点信息
                if (node.length > 0) {
                    me.loadingOp = true;
                    let page = {'size': 10, 'page': this.index, pId: me.selectItem[0].id};
                    Util.axios.post('/ms/menus/queryOp', qs.stringify(page)).then(res => {
                        var data = res.data;
                        if (data.result) {
                            me.total = data.data.total;
                            me.rows = data.data.rows;
                            me.rows.forEach(ref=>{

                                let obj = me.hashMenus[ref.MENUID];
                                if(obj)
                                {
                                    ref._checked = true;
                                }
                                else {
                                    ref._checked = false;
                                }
                            });
                        }
                        me.loadingOp = false;
                    });
                }
                else {

                }
            },
            checkMenu(nodeKey) {
            },
            selectRole(selection, row) {
                this.checkRows.push(row.MENUID);
            },
            selectAllRole(selection, row) {
                let me = this;
                if (selection) {
                    selection.forEach(ref => {
                        me.checkRows.push(ref.MENUID);
                    });
                }
            },
            selectCancelRole(selection, row) {
                let me = this;
                let rM = row.MENUID;
                me.checkRows.forEach((ref, index) => {
                    if (ref == rM) {
                        me.checkRows.splice(index, 1);
                    }
                });
            },
            breakContent()
            {
                this.spinShowWin = false;
            }
        },
        created() {
            //查询角色
            this.queryRoleList();
            //查询菜单列表
            this.loadMenuData();
        }
    }
</script>
